package com.chy.order_meal.controller;


import com.chy.order_meal.bean.ChyResponse;
import com.chy.order_meal.po.User;
import com.chy.order_meal.service.UserService;
import com.chy.order_meal.utility.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/user/")
public class userController {

    @Autowired
    private UserService service;

    @PostMapping("save")
    @ResponseBody
    public ChyResponse save(User user){
        Boolean check = user.check();
        if (!check){
            return new ChyResponse(false,"参数异常",null);
        }

        //检查邮箱 电话是否已经存在
        Map<String,String> userCheck = service.checkUser(user.getEmail(),user.getPhone());
        if(userCheck != null){
            return new  ChyResponse(false,"参数异常",userCheck);
        }

        try{
            User u = service.save(user);
            return ChyResponse.simpSuccess(u);
        }catch (Exception e){
            return new ChyResponse(false,"保存失败",null);
        }



    }

    @PostMapping("login")
    @ResponseBody
    public ChyResponse login(User user, HttpSession session){
            String email = user.getEmail();
            String phone =user.getPhone();
            String password = user.getPassword();

            if((Common.empty(email) && Common.empty(phone)) || Common.empty(password) ){
                return new ChyResponse(false,"参数异常",null);
            }


        try{
            Boolean success = service.login(email,phone,password);
            if(success){
                session.setAttribute("user",user);
                return ChyResponse.simpSuccess(user);
            }else{
                String msg = "登录账号或密码异常";
                return new ChyResponse(false,msg,msg);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ChyResponse(false,"登录异常",null);
        }
    }

    @GetMapping("/xxx")
    @ResponseBody
    public String xxxx(){
        return "ooooooooooooooooo";
    }

    @GetMapping("/isLogin")
    @ResponseBody
    public ChyResponse isLogin(HttpSession session){
        User user = (User) session.getAttribute("user");
        session.getAttribute("user");
        ChyResponse result = new ChyResponse();
        if(user == null){
            result.setSuccess(false);
            result.setMsg("账号未登录");
        }else{
            result.setSuccess(true);
            result.setMsg("账号已登录");
            result.setData(user);
        }
        return result;
    }




}
